﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;

namespace Servicios.Calificaciones.Helpers
{
    public class ReportGenerator
    {
        public HttpResponseMessage CallReportGenerator(string reportPath, string formato, Dictionary<string, string> parameters, string reporte, string rutaArchivosTemporales)
        {
            using (var report = new Report
            {
                ReportServerPath = reportPath,
                Format = (formato.ToUpper().Equals("PDF")) ? ReportFormats.Pdf :
                         (formato.ToUpper().Equals("XLS")) ? ReportFormats.Xlsx :
                                                     ReportFormats.Html,
                ReportPath = reporte,
                Params = parameters
            })
            {
                report.Credentials = new System.Net.NetworkCredential()
                {
                    UserName = ConfigurationManager.AppSettings["ReportUser"],
                    Password = ConfigurationManager.AppSettings["ReportUserPassword"]
                };

                var ms = new MemoryStream();
                report.Render2().CopyTo(ms);

                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

                var path = rutaArchivosTemporales + "\\" + Guid.NewGuid() + reporte + "." + formato.ToLower();

                using (var fStream = new FileStream(path, FileMode.OpenOrCreate))
                {
                    var dat = ms.ToArray();
                    fStream.Write(dat, 0, dat.Length);
                }

                ms.Close();

                var streamFile = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                result.Content = new StreamContent(streamFile);


                //result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/" + formato.ToLower());


                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = reporte + "." + formato.ToLower()
                };

                //if (path != null) File.Delete(path);

                return result;
            }
        }
    }
}